package com.smyh.util;

import java.util.Calendar;
import java.util.Date;

public class DateUtil101V2 {


	/**
	 * 功能：根据传入的时间参数，按照101协议格式返回数组.101规定有2、3、7个字节三种时间表示形式，默认为7个字节 作者：zhuchunsheng
	 * 参数：@param date 参数：@param byteNum 字节数 参数：@return 返回值：byte[] 日期时间：2013-7-18
	 * 下午1:00:15
	 */
	public static byte[] getDateBytes(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int millsSecondMS = cal.get(Calendar.MILLISECOND) + cal.get(Calendar.SECOND) * 1000;
		int minites = cal.get(Calendar.MINUTE);
		int hours = cal.get(Calendar.HOUR_OF_DAY);
		int daysOnMon = cal.get(Calendar.DAY_OF_MONTH);
		int months = cal.get(Calendar.MONTH) + 1;
		int years = cal.get(Calendar.YEAR) % 100;
		byte[] timeBytes = new byte[7];
		// 默认为7字节的
		timeBytes[0] = (byte) millsSecondMS;
		timeBytes[1] = (byte) (millsSecondMS >> 8);
		timeBytes[2] = (byte) minites;
		timeBytes[3] = (byte) hours;
		timeBytes[4] = (byte) ((int)  daysOnMon);
		timeBytes[5] = (byte) months;
		timeBytes[6] = (byte) years;
		return timeBytes;
	}

	/**
	 * 功能：根据101协议的时间字节数组，转换成时间的时间对象：101规定有2、3、7个字节三种时间表示形式，默认为7个字节
	 * 和上面的方法：getDateBytes(Date date)是一个逆运算 作者：zhuchunsheng 参数：@param dateBytes
	 * 参数：@return 返回值：Date 日期时间：2013-7-18 下午1:01:10
	 */
	public static Date getDateObj(byte[] dateBytes) {
		// 获取协议的基本配置信息,为空则使用默认的设置
		Date date = null;
		Calendar cal = Calendar.getInstance();
		int millsSecondMS = (int) (dateBytes[0] & 0xff) + (int) ((dateBytes[1] & 0xff) * 256);
		int minites = dateBytes[2] & 0x3f;
		int hours = dateBytes[3] & 0x1f;
		int daysOnMon = dateBytes[4] & 0x1f;
		int months =  (dateBytes[5] & 0xf) - 1;
		int years = (dateBytes[6] & 0x7f) + 2000;
		cal.set(Calendar.MILLISECOND, millsSecondMS % 1000);
		cal.set(Calendar.SECOND, millsSecondMS / 1000);
		cal.set(Calendar.MINUTE, minites);
		cal.set(Calendar.HOUR_OF_DAY, hours);
		cal.set(Calendar.DAY_OF_MONTH, daysOnMon);
		cal.set(Calendar.MONTH, months);
		cal.set(Calendar.YEAR, years);
		date = cal.getTime();
		return date;
	}
	/**
	 * 功能：根据101协议的时间字节数组，转换成时间：101规定有2、3、7个字节三种时间表示形式，默认为7个字节
	 * 和上面的方法：getDateBytes(Date date)是一个逆运算 作者：zhuchunsheng 参数：@param dateBytes
	 * 参数：@return 返回值：Long 毫秒数
	 */
	public static Long getLongTimes(byte[] dateBytes) {
		// 获取协议的基本配置信息,为空则使用默认的设置
		Date date = null;
		Calendar cal = Calendar.getInstance();
		int hours = dateBytes[3] & 0x1f;
		int daysOnMon = dateBytes[4] & 0x1f;
		int months =  (dateBytes[5] & 0xf) - 1;
		int years =  (dateBytes[6] & 0x7f) + 2000;
		cal.set(Calendar.HOUR_OF_DAY, hours);
		cal.set(Calendar.DAY_OF_MONTH, daysOnMon);
		cal.set(Calendar.MONTH, months);
		cal.set(Calendar.YEAR, years);
		date = cal.getTime();		
		return date.getTime();
	}
}
